<?php


/**
 * 统计指定目录中的文件和文件夹数量
 * @author arvin
 * @param string $filepath 
 * @result array
 */
function statfile($filepath)
{
	if(file_exists($filepath)){
		static $folder,$file;
		$hander = opendir($filepath);
		while(false != ($filename = readdir($hander))){
			if(is_dir($filepath.'/'.$filename) && ($filename != '.' && $filename != '..')){
				$folder++;
				statfile($filepath.'/'.$filename);
			}else{
				if(is_file($filepath.'/'.$filename))
					$file++;
			}
		}
		closedir($hander);
	}else{
		print 'directory not exists!';
	}

	return array('folder'=>$folder,'file'=>$file);
}

/**
 * 计算程序执行时间差
 * @auther arvin
 * @param int $len
 * @return float
 */
function get_microtime($len=3)
{
	list($msecond,$second) = explode(' ',microtime());
	return bcadd($msecond,$second,$len);
}

/**
 * 递归创建多级目录
 * @param string $path
 * @return void
 */
function createFolder($path)
{
	if(!file_exists($path)){
		createFolder(dirname($path));
		mkdir($path,0777);
	}
}

/**
 * 删除指定目录及其子项 
 * @param string $directory
 * @param boolean [optional]- whether a virtual directory
 * @return boolean
 */
function deldirectory($directory,$virtual=false)
{
	$ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) && $handle = opendir($dir)){   
		/*如果返回目录条目*/
        while ($file = readdir($handle)){
            if ($file == '.' || $file == '..'){
                continue;
            }elseif (is_dir($dir.$ds.$file)){
                deldirectory($dir.$ds.$file);
            }else{
                unlink($dir.$ds.$file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    }else{
        return false;
    }
}

/**
 * 获取客户端ip
 * @param void
 * @return string $ip
 */
function getClientIp()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		return $ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		return $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
	    return $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
		return $ip = $_SERVER['REMOTE_ADDR'];
    }
}

/**
 * 错误日志记录
 * error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE)
 *
 */
 function error_info($errno,$errstr,$errfile,$errline)
 {
	//ini_set('error_log','D:/error.log');
	ini_set('log_errors','On');
	ini_set('display_errors','Off');
	$time = date('Y-n-j H:i:s',time());
	
	$message = "$time [$errno] $errstr,$errfile,$errline";
	error_log($message);
 }

 // cookie 跨域
 header('P3P: CP='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR'');

// Curl socket file_get_contents POST数据
/**
 * socket
 * $post_string = "app=socket&version=beta";
 * request_by_socket('facebook','/restServer.php',$post_string);   
 */
 function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){
	$socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout);
	if(!$socket) die("$errstr($errno)");

	$header = "POST $remote_path HTTP/1.0\r\n"; 
	$header .= "User-Agent: Socket Example\r\n";
	$header .= "HOST: $remote_server\r\n";
	$header .= "Content-type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-length: ".strlen($post_string)+8."\r\n";
	$header .= "Accept:*/*\r\n";
	$header .= "\r\n mypost=$post_string\r\n";

	fwrite($socket,$header);

	$response = "";
	while($str = trim(fgets($socket,4096))){
		$response .= $str;
	}

	$data = "";
	while(!feof($socket)){
		$data .= fgets($socket,4096);
	}
	
	return $data;
 }


/** 
* Curl版本 
* 使用方法： 
* $post_string = "app=request&version=beta"; 
* request_by_curl('http://facebook.cn/restServer.php',$post_string); 
*/ 
function request_by_curl($remote_server,$post_string){

    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_URL,$remote_server); 
    curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
    curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta"); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    
	return $data; 

}

/** 
* 其它版本 
* 使用方法： 
* $post_string = "app=request&version=beta"; 
* request_by_other('http://facebook.cn/restServer.php',$post_string); 
*/ 
function request_by_other($remote_server,$post_string){ 
    
	$context = array( 
        'http'=>array( 
            'method'=>'POST', 
            'header'=>'Content-type: application/x-www-form-urlencoded'."\r\n". 
                      'User-Agent : Jimmy\'s POST Example beta'."\r\n". 
                      'Content-length: '.strlen($post_string)+8, 
            'content'=>'mypost='.$post_string) 
         ); 
    $stream_context = stream_context_create($context); 
    $data = file_get_contents($remote_server,FALSE,$stream_context); 
    return $data; 

}


function get_hash_table($table,$userid) {
	$str = crc32($userid);
	if($str < 0){
		$hash = "0".substr(abs($str), 0, 1);
	}else{
		$hash = substr($str, 0, 2);
	}
	return $table."_".$hash;
}

//echo get_hash_table('message','user18991');  //结果为message_10
//echo get_hash_table('message','user34523'); //结果为message_13

function clocking(){
	// 关掉浏览器，PHP脚本也可以继续执行.
	ignore_user_abort();
	// 程序无限制的执行下去
	set_time_limit(0);
	$interavl = 60*30;
	do{
		// TODO
		sleep($interval);
	}while(true);
}


?>